//
//  ViewController.m
//  Test_UIWebView
//
//  Created by Zhao Mingming on 16/1/11.
//  Copyright © 2016年 MMZhao. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<UIWebViewDelegate>
{
  UIActivityIndicatorView *_indicator;
}

@property (nonatomic,strong)  UIAlertView *alertView;

@end

//#define kTestURL           @"http://www.pasdasdagyer.comasd"
//#define kTestURL           @"https://idmsa.apple.com/IDMSWebAuth/authenticate"


#define kTestEnvironment  0

#if kTestEnvironment

#define kURL           @"http://www.sina_test.com.cn"

#else

#define kURL           @"http://www.sina.com.cn"

#endif

@implementation ViewController


- (void)viewDidLoad {
  [super viewDidLoad];
  
  UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
  [self.view addSubview:webView];
  webView.delegate = self;
  
  NSURL *url = [NSURL URLWithString:kURL];
  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
  request.timeoutInterval = 3;
  [webView loadRequest:request];
  
  [self becomeObserver];
}

- (void)becomeObserver
{
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(applicationEnterForeground)
                                               name:UIApplicationWillEnterForegroundNotification
                                             object:nil];
}

- (void)applicationEnterForeground
{
  if (_alertView) {
    [_alertView dismissWithClickedButtonIndex:_alertView.cancelButtonIndex animated:NO];
  }
  NSLog(@"-----继续加载---");
}

- (void)viewDidDisappear:(BOOL)animated
{
  [super viewDidDisappear:animated];
  
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark -
#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
  [self showLoadingIndicator];
  NSLog(@"超时时间 ： %f",request.timeoutInterval);
  NSHTTPURLResponse *response = nil;
  NSError *error;
  [NSURLConnection sendSynchronousRequest:request
                        returningResponse:&response
                                    error:&error];
  
  NSLog(@"response statusCode # %ld",(long)[response statusCode]);
  NSLog(@"errorCode # %ld",(long)error.code);

  if (error.code == -1012) {
    [self hideLoadingIndicator];
    [self didFailLoadWithError:error.code];
    [webView stopLoading];
    return NO;
  }
  return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
  NSLog(@"----开始加载");
  [self showLoadingIndicator];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
  NSLog(@"----加载完成");
  [self hideLoadingIndicator];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
  NSLog(@"-------------------%ld",(long)error.code);
  NSLog(@"webView error %@ #---------# error message %@",webView.debugDescription,error.debugDescription);
  [self hideLoadingIndicator];
  [self didFailLoadWithError:error.code];
}

/**
 *  UIWebView ErroCode
 */
//kCFURLErrorUnknown                       = -998,
//kCFURLErrorCancelled                     = -999,
//kCFURLErrorBadURL                        = -1000,
//kCFURLErrorTimedOut                      = -1001,  "The request timed out."
//kCFURLErrorUnsupportedURL                = -1002,
//kCFURLErrorCannotFindHost                = -1003,  "lost host"
//kCFURLErrorCannotConnectToHost           = -1004,
//kCFURLErrorNetworkConnectionLost         = -1005,
//kCFURLErrorDNSLookupFailed               = -1006,
//kCFURLErrorHTTPTooManyRedirects          = -1007,
//kCFURLErrorResourceUnavailable           = -1008,
//kCFURLErrorNotConnectedToInternet        = -1009,  "The Internet connection appears to be offline."
//kCFURLErrorRedirectToNonExistentLocation = -1010,
//kCFURLErrorBadServerResponse             = -1011,
//kCFURLErrorUserCancelledAuthentication   = -1012,   用户取消了身份验证
//kCFURLErrorUserAuthenticationRequired    = -1013,
//kCFURLErrorZeroByteResource              = -1014,
//kCFURLErrorCannotDecodeRawData           = -1015,
//kCFURLErrorCannotDecodeContentData       = -1016,
//kCFURLErrorCannotParseResponse           = -1017,
//kCFURLErrorInternationalRoamingOff       = -1018,
//kCFURLErrorCallIsActive                  = -1019,
//kCFURLErrorDataNotAllowed                = -1020,
//kCFURLErrorRequestBodyStreamExhausted    = -1021,
//kCFErrorDomainCFNetwork                  = -1022,  返回安全链接 在iOS 9 上 要求 必须是 https 协议
//kCFURLErrorFileDoesNotExist              = -1100,
//kCFURLErrorFileIsDirectory               = -1101,
//kCFURLErrorNoPermissionsToReadFile       = -1102,
//kCFURLErrorDataLengthExceedsMaximum      = -1103,

/**
 *  HTTP 访问 ErrorCode
 */
// 200  访问成功
// 401  未授权，登陆失败
// 403  访问限制
// 404  页面不存在


- (void)didFailLoadWithError:(NSInteger)errorCode
{
  NSString *errorMessage = nil;
  switch (errorCode) {
    case -1001:
      errorMessage = @"页面加载超时，请稍后重试!";
      break;
      
    case -1003:
      errorMessage = @"网络连接错误，请检查网络连接是否正确!";
      break;

    case -1009:
      errorMessage = @"无网络,请连接网络后重试!";
      break;
      
    case -1012:
      errorMessage = @"用户无权限访问";
      break;
      
    default:
      errorMessage = [NSString stringWithFormat:@"页面错误，Error Code : %ld",(long)errorCode];
      break;
  }
  [self showErrorMessage:errorMessage];
}

- (void)showErrorMessage:(NSString *)errorMessage
{
  _alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                          message:errorMessage
                                         delegate:nil
                                cancelButtonTitle:@"确定"
                                otherButtonTitles:nil, nil];
  [_alertView show];
}

#pragma mark -
#pragma mark   UIActivityIndicatorView
- (void)showLoadingIndicator
{
  [self hideLoadingIndicator];
  self.view.userInteractionEnabled = NO;
  
  _indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  _indicator.color = [UIColor colorWithRed:64 / 255.0 green:169 / 255.0 blue:224 / 255.0 alpha:1.0];
  
  [self.view addSubview:_indicator];
  [self.view bringSubviewToFront:_indicator];
  
  CGFloat centerX = CGRectGetMidX(self.view.bounds);
  CGFloat centerY = CGRectGetMidY(self.view.bounds) - 50;
  CGPoint center  = CGPointMake(centerX, centerY);
  _indicator.center = center;
  
  [_indicator startAnimating];
}

- (void)hideLoadingIndicator
{
  self.view.userInteractionEnabled = YES;
  if (_indicator) {
    [_indicator stopAnimating];
    [_indicator removeFromSuperview];
    _indicator = nil;
  }
}

@end
